<template>
  <div class="alert">
    <div class="alert-main" v-for="item in notices" :key="item.name">
      <div class="alert-content">{{ item.content }}</div>
    </div>
  </div>
</template>

<script>
/**
 * Alert 组件不同于常规的组件使用方式，它最终是通过 JS 来调用的，因此组件不用预留 props 和 events 接口
 */
let send = 0;
function getUid() {
  return "alert_" + send++;
}
export default {
  name: "BaseAlter",
  data() {
    return {
      notices: []
    };
  },
  methods: {
    add(notice) {
      const name = getUid();
      let _notice = Object.assign(
        {
          name: name
        },
        notice
      );
      this.notices.push(_notice);
      const duration = notice.duration;
      setTimeout(() => {
        this.remove(name); //删除的是'alter_001'的名称
      }, duration * 1000);
    },
    remove(name) {
      const notices = this.notices;
      for (let i = 0; i < notices.length; i++) {
        if (notices[i].name !== name) break;
        this.notices.splice(i, 1);
      }
    }
  }
};
</script>

<style lang="stylus" scoped>
.alert {
  position: fixed
  width: 100%
  top: 160px
  left: 0
  text-align: center
  pointer-events: none
}
.alert-content {
  display: inline-block
  padding: 8px 16px
  background: #fff
  border-radius: 3px
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2)
  margin-bottom: 8px
}
</style>
